//
//  ComposeViewController.swift
//  SwiftWeibo
//
//  Created by Lucky on 16/5/13.
//  Copyright © 2016年 Lucky. All rights reserved.
//

import UIKit
import SVProgressHUD

class ComposeViewController: UIViewController {
    
    var inputToolBarBottomConstraint: NSLayoutConstraint?
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        
        addChildViewController(emoticonVC)
        
        //注册通知监听键盘的弹出和消失
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ComposeViewController.keyboardChangeFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        // 设置导航条
        setupNav()
        
        // 初始化输入框
        setupInutView()
        
        // 设置输入框顶部工具条
        setupInputToolBar()
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        textView.becomeFirstResponder()
        
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        
        textView.resignFirstResponder()
    }
    
    private func setupNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(ComposeViewController.close))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(ComposeViewController.send))
        navigationItem.rightBarButtonItem?.enabled = false
        
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 32))
        let label1 = UILabel()
        label1.text = "发送微博"
        label1.textAlignment = NSTextAlignment.Center
        label1.font = UIFont.systemFontOfSize(13)
        label1.sizeToFit()
        titleView.addSubview(label1)
        
        let label2 = UILabel()
        label2.text = UserAccount.loadAccount()?.screen_name
        label2.textAlignment = NSTextAlignment.Center
        label2.font = UIFont.systemFontOfSize(15)
        label2.textColor = UIColor.darkGrayColor()
        label2.sizeToFit()
        titleView.addSubview(label2)
        
        label1.translatesAutoresizingMaskIntoConstraints = false
        titleView.addConstraint(NSLayoutConstraint(item: label1, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: titleView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0.0))
        titleView.addConstraint(NSLayoutConstraint(item: label1, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: titleView, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0.0))
        
        label2.translatesAutoresizingMaskIntoConstraints = false
        titleView.addConstraint(NSLayoutConstraint(item: label2, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: titleView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0.0))
        titleView.addConstraint(NSLayoutConstraint(item: label2, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: titleView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0.0))
        
        navigationItem.titleView = titleView
    }
    
    private func setupInutView() {
        view.addSubview(textView)
        
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        textView.translatesAutoresizingMaskIntoConstraints = false
        
        view.addConstraint(NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0.0))
        view.addConstraint(NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0.0))
        view.addConstraint(NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Trailing, multiplier: 1.0, constant: 0.0))
        view.addConstraint(NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0.0))
        
        textView.addSubview(placeholderLabel)
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        textView.addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: textView, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 5.0))
        textView.addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: textView, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 8.0))
    }
    
    private func setupInputToolBar() {
        view.addSubview(inputToolBar)
    
        var items = [UIBarButtonItem]()
        
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "selectPicture"],
                            
                            ["imageName": "compose_mentionbutton_background"],
                            
                            ["imageName": "compose_trendbutton_background"],
                            
                            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
                            
                            ["imageName": "compose_addbutton_background"]]
        
        for dict in itemSettings {
            let item = UIBarButtonItem(imageName: dict["imageName"]!, target: self, action: Selector(dict["action"] ?? "other"))
            
            items.append(item)
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        inputToolBar.items = items

        inputToolBar.translatesAutoresizingMaskIntoConstraints = false
        
        view.addConstraint(NSLayoutConstraint(item: inputToolBar, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: UIScreen.mainScreen().bounds.width))
        inputToolBarBottomConstraint = NSLayoutConstraint(item: inputToolBar, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0.0)
        view.addConstraint(inputToolBarBottomConstraint!)
        view.addConstraint(NSLayoutConstraint(item: inputToolBar, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0.0))
    }
    
    // MARK: - 键盘弹出和消失处理
    func keyboardChangeFrame(notify: NSNotification) {
        let value = notify.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
        let rect = value.CGRectValue()
        
        let height = UIScreen.mainScreen().bounds.height
        inputToolBarBottomConstraint?.constant = -(height - rect.origin.y)
        
        let duration = notify.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
        
        let curve = notify.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
        
        UIView.animateWithDuration(duration.doubleValue) {
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve.integerValue)!)
            self.view.layoutIfNeeded()
        }
    }
    
    // MARK: - navigationBar按钮点击
    func close() -> () {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func send() -> () {
        
        let path = "2/statuses/update.json"
        let params = ["access_token": UserAccount.loadAccount()!.access_token!, "status": textView.emoticonAttributedText()]
        
        NetworkTools.shareNetworkTools().POST(path, parameters: params, success: { (_, JSON) in
            SVProgressHUD.showSuccessWithStatus("发送成功")
            }) { (_, error) in
                SVProgressHUD.showErrorWithStatus("发送失败")
        }
        
    }
    
    // MARK: - 输入工具条按钮点击
    func selectPicture() {
        
    }
    
    func inputEmoticon() {
        textView.resignFirstResponder()
        textView.inputView = (textView.inputView == nil) ? emoticonVC.view : nil
        textView.becomeFirstResponder()
    }
    
    func other() {
        
    }
    
    // MARK: - 懒加载
    private lazy var textView: UITextView = {
        let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(17)
        tv.delegate = self
        return tv
    }()

    private lazy var placeholderLabel: UILabel = {
        let label = UILabel()
        label.text = "分享新鲜事..."
        label.textColor = UIColor.darkGrayColor()
        label.font = UIFont.systemFontOfSize(self.textView.font!.lineHeight)
        return label
    }()
    
    private lazy var inputToolBar: UIToolbar = UIToolbar()

    private lazy var emoticonVC: EmoticonViewController = EmoticonViewController { (emoticon) in
        self.textView.insertEmoticon(emoticon)
    }
}

extension ComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        placeholderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}


